package ui.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.Menu
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import com.example.mynewsapp.R
import ui.fragment.CategoryFragment
import ui.fragment.DownloadFragment
import ui.fragment.MainFragment
import ui.fragment.SearchFragment
import ui.fragment.SettingFragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.snackbar.Snackbar
import io.karn.notify.Notify

// 2025-1-20
// let's do a template app
// why not, I do this all out of fun


// design & architecture:
// SplashActivity boot the app and set shared preference
// AccountActivity load two fragment: Login and SignUp
// MainActivity load MainFragment and the rest ... Fragment





class MainActivity : AppCompatActivity() {

    private val PREFS_IS_LOGGED_IN = "isLoggedIn"


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {

        return true

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        setContentView(R.layout.activity_main)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 一开始就加载MainFragment，不必要点击再加载
        if (savedInstanceState == null) {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.main_fragment, MainFragment())
                .commit();
        }


        clickBottomNavigation()

        // 进入主activity就发送一个通知
        sendANotification()


    }


    /** 底部导航栏的点击事件*/
    private fun clickBottomNavigation() {
        val bottomNavMenu: BottomNavigationView = findViewById(R.id.navMenu)
        bottomNavMenu.setOnItemSelectedListener { whichItem ->
            when (whichItem.itemId) {
                R.id.bottom_home -> loadFragment(MainFragment())
                R.id.bottom_category -> loadFragment(CategoryFragment())
                R.id.bottom_save -> loadFragment(DownloadFragment())
                R.id.bottom_search -> loadFragment(SearchFragment())
                R.id.bottom_setting -> loadFragment(SettingFragment())
                else -> loadFragment(MainFragment())
            }
            true
        }
    }

    /** 加载fragment*/
    private fun loadFragment(fragmentReplace: Fragment) {
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.main_fragment, fragmentReplace)
            .commit()
    }

    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {

        } else {
            // Explain to the user that the feature is unavailable because the
            // features requires a permission that the user has denied. At the
            // same time, respect the user's decision. Don't link to system
            // settings in an effort to convince the user to change their
            // decision.
        }
    }


    private fun sendANotification() {
        // 申请通知权限代码
        when {
            ContextCompat.checkSelfPermission(
                this, Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED -> {
                // You can use the API that requires the permission.
            }

            shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) -> {
                Snackbar.make(
                    findViewById(R.id.main),
                    "Notification blocked",
                    Snackbar.LENGTH_LONG
                ).setAction("Settings") {
                    // Responds to click on the action
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    val uri: Uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                }.show()
            }

            else -> {
                // You can directly ask for the permission.
                // The registered ActivityResultCallback gets the result of this request.
                if (Build.VERSION.SDK_INT >= 33) {
                    requestPermissionLauncher.launch(
                        Manifest.permission.POST_NOTIFICATIONS
                    )
                }
            }
        }

        /** ref link: https://github.com/Karn/notify*/
        Notify
            .with(this)
            .content { // this: Payload.Content.Default
                title = "你好呀"
                text = "哈哈哈"
            }
            .show()
    }


}